<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box1 {
        width: 50px;
        height: 50px;
        position: absolute;
        background-color: aqua;
      }
    </style>
  </head>
  <body>
    <div class="box1"></div>
    <script>
      var boxEle = document.querySelector(".box1");
      //在按下的瞬间 光标会到左上角 我们需要光标相对盒子位置不变
      boxEle.onmousedown = function (e) {
        boxEle.onmousemove = function (e) {
          var e = e || window.e;
          var x = e.clientX;
          var y = e.clientY;
          boxEle.style.left = x + "px";
          boxEle.style.top = y + "px";
        };
        boxEle.onmouseup = function (e) {
          //当鼠标抬起时  清除move的绑定事件
          var e = e || window.e;
          var x = e.clientX;
          var y = e.clientY;
          boxEle.style.left = x + "px";
          boxEle.style.top = y + "px";
          boxEle.onmousemove = "";
        };
      };
    </script>
  </body>
</html>
